package test.n00500;


import java.util.ArrayList;
import java.util.List;

import static utils.Tools.listOf;

public class Problem00540 {
    public static void main(String[] args) {
        println(new int[][]{
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        });
    }

    public static void println(int[][] matrix) {
        Solution ss = new Solution();
        System.out.println(listOf(matrix) + "," + ss.spiralOrder(matrix));
    }

    public static class Solution {

        /**
         * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
         *
         * @param matrix
         * @return
         */
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();

            int ROW = matrix.length, COL = matrix[0].length;
            boolean[][] visited = new boolean[ROW][COL];
            int n = ROW * COL;

            // 方向, {col, row}
            int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
            int row = 0, col = 0;
            int directionIndex = 0;
            for (int i = 0; i < n; i++) {
                result.add(matrix[row][col]);
                visited[row][col] = true;

                int nextRow = row + directions[directionIndex][1], nextCol = col + directions[directionIndex][0];
                if (nextRow < 0 || nextCol < 0 || nextRow >= ROW || nextCol >= COL || visited[nextRow][nextCol]) {
                    directionIndex = (directionIndex + 1) % 4;
                }

                row = row + directions[directionIndex][1];
                col = col + directions[directionIndex][0];
            }
            return result;
        }
    }
}
